package face.pay.common.enterprise.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.oss.sdk.OSSUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import face.pay.common.enterprise.service.IMchMediaBaseServcice;
import face.pay.dao.*;
import face.pay.entity.*;
import face.pay.server.IServerAddressServer;
import face.pay.util.FaceFileUtils;
import face.pay.util.HttpClientUtil;
import face.pay.util.ResultMessage;
import face.pay.util.ValidatorUtil;
import face.pay.util.bean.JavaBeanUtils;
import face.pay.util.page.PageData;
import face.pay.util.page.PageParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Auther: zkj
 * @Date: 2019/8/29 12:13
 * @Description:
 */
@Service
@Slf4j
public class MchMediaBaseServiceImpl implements IMchMediaBaseServcice {

    @Autowired
    private OemConfigInfoDao oemConfigInfoDao;

    @Autowired
    private OemInfoDao oemInfoDao;

    @Autowired
    private FileInfoDao fileInfoDao;

    @Autowired
    private IServerAddressServer iServerAddress;

    @Autowired
    private WeChatMchInfoDao weChatMchInfoDao;

    @Autowired
    MchApplymentInfoDao mchApplymentInfoDao;



    /**
     * @param enterpriseInfo
     * @param file
     * @return
     * 商户资料中 图片信息的保存以及上传OSS
     * 以及上传微信
     */
    @Override
    @Transactional
    public ResultMessage mediaload(WeChatMchInfo weChatMchInfo, byte[] bytes,String fileName, String keyName, UserInfo loginUser) throws Exception {

        Integer oemId  =  loginUser.getOemId();

        OemConfigInfo configInfo =  this.oemConfigInfoDao.getByOemId(oemId);

        String faceKey  = configInfo.getFaceKey();

        String hash     =    DigestUtils.md5DigestAsHex(bytes);

        String fileBody =   FaceFileUtils.byte2hex(bytes);


        Map<String,Object> map = new HashMap<>();

        map.put("oemId",String.valueOf(oemId));

        Map<String,String>  data = new HashMap<>();
        data.put("fileName",fileName);
        data.put("body",fileBody);
        data.put("userId",String.valueOf(weChatMchInfo.getUserId()));

        String sign =  WXPayUtil.generateSignature(data,faceKey, WXPayConstants.SignType.MD5);
        map.put("sign",sign);
        map.put("data",data);

        String json = JSON.toJSONString(map);

        String resultMessae = HttpClientUtil.doPostJson(iServerAddress.getFileUploadUrl(),json);

        log.info(resultMessae);
        if(StringUtils.isNotBlank(resultMessae)){

            ResultMessage resultMessage = JSON.parseObject(resultMessae,ResultMessage.class);

            if(new Integer(1).equals(resultMessage.getCode())){

                /**
                 * 更新物料信息
                 */
                Map<String,String> resultMap = (Map<String,String>) resultMessage.getData();

                Map<String,Object> param = new HashMap<>();

                param.put("id",weChatMchInfo.getId());
                param.put(keyName,resultMap.get("media_id"));
                this.weChatMchInfoDao.updateImg(param);

            }
            return  resultMessage;
        }else {
            return ResultMessage.createFail("调用链接失败");

        }
    }

    @Override
    public byte[] getMedia(String mediaId,UserInfo loginUser) {

        //设置下载的文件的名称-该方式已解决中文乱码问题

        Integer oemId = loginUser.getOemId();

        OemConfigInfo configInfo =  this.oemConfigInfoDao.getByOemId(oemId);

        FileInfo fileInfo =  this.fileInfoDao.getByMediaId(mediaId);

        byte[] bytes =  new byte[]{};
        try{
            bytes =  OSSUtils.getOSSBytes(configInfo.getEndPoint(),configInfo.getAccessKeyId(),configInfo.getAccessKeySecret(),configInfo.getBucket(),fileInfo.getFullName());
        }catch (Exception e){
            log.error("上传图片异常",e);
        }
        return  bytes;

    }

    /**
     * 商家进件管理
     * @param enterpriseInfo
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage subinfo(WeChatMchInfo weChatMchInfo, UserInfo loginUser) throws  Exception {

        Integer oemId = loginUser.getOemId();


        /**
         * 检查商户进件列表
         * 如果发现有没有处理或者已经通过的记录
         * 则不提交无效
         */
        log.info("商户进件oemId "+oemId);

        MchApplymentInfo applymentInfo  =  new MchApplymentInfo();
        applymentInfo.setOemId(weChatMchInfo.getOemId());
        applymentInfo.setUserId(weChatMchInfo.getUserId());
        List<MchApplymentInfo> list = this.mchApplymentInfoDao.queryList(applymentInfo);

        if(list.size()>0){
            MchApplymentInfo apply = list.get(0);
            String state  =apply.getApplyment_state();

            if(!"REJECTED".equals(state)){
               return  ResultMessage.createFail("最近提交的申请未处理或已通过请勿重复提交");
            }
        }
        /**
         * 默认提交保存最新信息
         */
        this.weChatMchInfoDao.update(weChatMchInfo);

        OemConfigInfo   configInfo =  this.oemConfigInfoDao.getByOemId(oemId);

        String faceKey  = configInfo.getFaceKey();

        MchApplymentInfo mchApplymentInfo  =  new MchApplymentInfo();

        BeanUtils.copyProperties(weChatMchInfo,mchApplymentInfo);

        /**
         * 排除ID 字段
         */
        mchApplymentInfo.setId(null);
        mchApplymentInfo.setRate(String.valueOf(weChatMchInfo.getWxFinalRate()));
        /**
         * 验证非空
         */

        Map<String,StringBuffer> validateMap= ValidatorUtil.validate(mchApplymentInfo);

        if(validateMap.isEmpty()){
            Map<String,Object> param = new HashMap<>();

            Map<String,String > data = JavaBeanUtils.toMap(mchApplymentInfo);
            data.put("userId",String.valueOf(mchApplymentInfo.getUserId()));
            data.put("omId",String.valueOf(oemId));

            String sign = WXPayUtil.generateSignature(data,faceKey);

            param.put("data", data);
            param.put("oemId",oemId);
            param.put("sign", sign);

            String json = JSON.toJSONString(param);

            /**
             * 发送给 开放接口
             */

            log.info("发送数据到开放接口中心:"+json);

            String resultMessae = HttpClientUtil.doPostJson(iServerAddress.getInfoApplyUrl(),json);

            log.info("开放接口中心返回数据:"+resultMessae);

            if(StringUtils.isNotBlank(resultMessae)){

                ResultMessage resultMessage = JSON.parseObject(resultMessae,ResultMessage.class);

                return  resultMessage;
            }else {
                return ResultMessage.createFail("调用链接失败");

            }

        }else {
            return  ResultMessage.createFail("资料信息不全",validateMap);

        }
    }


    @Override
    public PageData<MchApplymentInfo> queryPage(MchApplymentInfo mchApplymentInfo, PageParam pageParam, UserInfo loginUser) {

        PageHelper.startPage(pageParam.getPageNo(),pageParam.getPageSize());

        List<MchApplymentInfo> applymentInfos = this.mchApplymentInfoDao.queryList(mchApplymentInfo);

        PageInfo<MchApplymentInfo> pageInfo = new PageInfo <MchApplymentInfo>(applymentInfos);

        PageData<MchApplymentInfo> pageData = new PageData<MchApplymentInfo>(pageInfo.getTotal(),applymentInfos);

        return  pageData;

    }

    /**
     * 检查申请状态
     * @param mchApplymentInfo
     * @param loginUser
     * @return
     */

    @Override
    public ResultMessage checkStatus(MchApplymentInfo mchApplymentInfo,UserInfo loginUser) {

        Integer oemId = loginUser.getOemId();

        log.info("微信查询 "+oemId);

        MchApplymentInfo applymentInfo =  this.mchApplymentInfoDao.getApplyMent(mchApplymentInfo);

        OemConfigInfo   configInfo =  this.oemConfigInfoDao.getByOemId(oemId);

        String faceKey  = configInfo.getFaceKey();


        if(applymentInfo!=null){

            try {

                Map<String,String > data = JavaBeanUtils.toMap(mchApplymentInfo);

                Map<String,Object> param = new HashMap<>();

                data.put("userId",String.valueOf(applymentInfo.getUserId()));
                data.put("omId",String.valueOf(oemId));
                data.put("applyId",String.valueOf(applymentInfo.getId()));
                String sign = WXPayUtil.generateSignature(data,faceKey);

                param.put("data", data);
                param.put("oemId",oemId);
                param.put("sign", sign);

                String json = JSON.toJSONString(param);

                /**
                 * 发送给 开放接口
                 */

                log.info("发送数据到开放接口中心:"+json);

                String resultMessae = HttpClientUtil.doPostJson(iServerAddress.getApplyStatusUrl(),json);

                log.info("开放接口中心返回数据:"+resultMessae);

                if(StringUtils.isNotBlank(resultMessae)){

                    ResultMessage resultMessage = JSON.parseObject(resultMessae,ResultMessage.class);

                    return  resultMessage;
                }else {
                    return ResultMessage.createFail("调用链接失败");

                }

            }catch (Exception e){
                log.error("进件查询出错",e);
            }

        }


        return ResultMessage.createFail("进件查询出错");
    }
}
